#include <iostream>
#include <string>
#include <unistd.h>

#define NUM 5

class Ticket
{
private:
    int tickets;
    pthread_mutex_t mtx;
public:
    
    Ticket(): tickets(1000)
    {
        pthread_mutex_init(&mtx, nullptr);
    }

    bool GetTicket()
    {
        bool res = true;
        pthread_mutex_lock(&mtx);
        if(tickets > 0)
        {
            usleep(1000);
            std::cout << "我是[" << pthread_self() << "] 我要抢的票是：" << tickets << std::endl;
            tickets--;
            printf("");
        }else {
            std::cout << "票已经被抢空" << std::endl;
            res = false;
        }
        pthread_mutex_unlock(&mtx);
        return res;
    }
    ~Ticket()
    {
        pthread_mutex_destroy(&mtx);
    }
};

void* ThreadRoutine(void* args)
{
    Ticket *t = (Ticket*)args;

    while(true)
    {
        if(!t->GetTicket())
        {
            break;
        }
    }
}

int main()
{
    Ticket* t = new Ticket();
    pthread_t tid[NUM];
    for(int i = 0; i < NUM; i++)
    {
        pthread_create(tid+i, nullptr, ThreadRoutine, (void*)t);
    }
    for(int i = 0; i < NUM; i++)
    {
        pthread_join(tid[i], nullptr);    
    }
    return 0;
}
